/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.store;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import ru.irenproject.BadInputException;
import ru.irenproject.Check;

import com.google.common.primitives.Longs;
import com.google.protobuf.ByteString;

public final class Kind {
  public static Kind get(long value) {
    return new Kind(value);
  }

  private final long fValue;

  private Kind(long value) {
    fValue = value;
  }

  public long value() {
    return fValue;
  }

  @Override public int hashCode() {
    return Longs.hashCode(fValue);
  }

  @Override public boolean equals(Object obj) {
    return (obj instanceof Kind) && (fValue == ((Kind) obj).fValue);
  }

  @Override public String toString() {
    return toHexString();
  }

  public String toHexString() {
    return Hex.encodeHexString(Longs.toByteArray(fValue));
  }

  public ByteString toByteString() {
    return ByteString.copyFrom(Longs.toByteArray(fValue));
  }

  public static Kind fromAlienHexString(String s) {
    Check.inputNotNull(s);

    byte[] ba;
    try {
      ba = Hex.decodeHex(s.toCharArray());
    } catch (DecoderException e) {
      throw new BadInputException(e);
    }

    Check.input(ba.length == Longs.BYTES);
    return get(Longs.fromByteArray(ba));
  }
}
